package com.dqhl.community.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dqhl.community.R;
import com.dqhl.community.adapter.ShoppingCarPayAdapter;
import com.dqhl.community.alipay.AliUtils;
import com.dqhl.community.alipay.PayResult;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.ExchangeCoupon;
import com.dqhl.community.model.OrderRecord;
import com.dqhl.community.model.PayMentCoupon;
import com.dqhl.community.model.ShopCartBean;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.wxpay.WxPaymentUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

/**
 * description: 立即付款页面
 * autour: guanluocang
 * date: 2016/10/18 15:01
 */
public class ShoppingCartPayActivity extends BaseActivity implements View.OnClickListener{

    private View view_bottom;
    private LinearLayout ll_add_gouwuche;
    private String pay_type;//支付类型
    protected SharedPreferences spUserInfo;
    private TextView tv_address;//收货地址
    private TextView tv_orderId;//订单号
    private String orderId;
    private String order_long;
    private TextView tv_account;
    private ImageView iv_payType;
    private ListView lv_goods;
    private ShoppingCarPayAdapter shoppingCarPayAdapter;
    private List<ShopCartBean> shopCartBeanList;
    private List<String> goods_idList; //需要付款的商品id
    private PayMentCoupon payMentCoupon_coupon;
    private ExchangeCoupon exchangeCoupon_coupon;

    private TextView tv_denomination;
    private TextView tv_deno;
    private TextView tv_coupontime;
    private TableLayout table_layout;
    private TextView tv_denomination_exchange;
    private TextView tv_deno_exchange;
    private TextView tv_coupontime_exchange;
    private TableLayout table_layout_exchange;
    private LinearLayout ll_coupon;
    private TextView tv_noneCoupon;
    private LinearLayout ll_exchange;
    private TextView tv_noneExchage;
    private String price;
    private TextView tv_shopping_allmoney;
    private TextView tv_top_title;
    private TextView tv_current_integral;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart_order);
        spUserInfo = getSharedPreferences(Constant.USER_INFO, MODE_PRIVATE);
        initView();
    }

    private void initView() {
        shopCartBeanList = (List<ShopCartBean>) getIntent().getSerializableExtra("goods_list");
        goods_idList = (List<String>) getIntent().getSerializableExtra("goods_id");
        payMentCoupon_coupon = (PayMentCoupon) getIntent().getSerializableExtra("coupon");
        exchangeCoupon_coupon = (ExchangeCoupon) getIntent().getSerializableExtra("exchange");
        price = getIntent().getStringExtra("price");
        Dlog.e(price);
        tv_current_integral = (TextView) findViewById(R.id.tv_current_integral);
        Dlog.e("GG "+user.getIntegral());
        tv_current_integral.setText(user.getIntegral());
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        tv_top_title.setText("确认订单");
        (view_bottom) = findViewById(R.id.view_botoom);
        view_bottom.setVisibility(View.GONE);
        (ll_add_gouwuche) = (LinearLayout) findViewById(R.id.ll_add_gouwuche);
        ll_add_gouwuche.setVisibility(View.GONE);
        tv_address = (TextView) findViewById(R.id.tv_address);
        String strAddress = spUserInfo.getString(Constant.ADDRESS, "");
        tv_address.setText(strAddress);
        (tv_orderId) = (TextView) findViewById(R.id.tv_orderId);
        orderId = getIntent().getStringExtra("order_id");
        order_long = getIntent().getStringExtra("order_long");
        tv_orderId.setText(order_long);
        pay_type = getIntent().getStringExtra("type");
        (tv_account) = (TextView) findViewById(R.id.tv_account);
        tv_denomination = (TextView) findViewById(R.id.tv_denomination);
        tv_deno = (TextView) findViewById(R.id.tv_deno);
        tv_coupontime = (TextView) findViewById(R.id.tv_coupontime);
        table_layout = (TableLayout) findViewById(R.id.table_layout);
        ll_coupon= (LinearLayout) findViewById(R.id.ll_coupon);
        tv_noneCoupon = (TextView) findViewById(R.id.tv_noneCoupon);
        ll_exchange = (LinearLayout) findViewById(R.id.ll_exchange);
        tv_noneExchage = (TextView) findViewById(R.id.tv_noneExchage);

        tv_denomination_exchange = (TextView) findViewById(R.id.tv_denomination_exchange);
        tv_deno_exchange = (TextView) findViewById(R.id.tv_deno_exchange);
        tv_coupontime_exchange = (TextView) findViewById(R.id.tv_coupontime_exchange);
        table_layout_exchange = (TableLayout) findViewById(R.id.table_layout_exchange);
        if(payMentCoupon_coupon == null){
            toast("1");
            ll_coupon.setVisibility(View.GONE);
            tv_noneCoupon.setVisibility(View.VISIBLE);
        }else {
            ll_coupon.setVisibility(View.VISIBLE);
            tv_noneCoupon.setVisibility(View.GONE);
            if(payMentCoupon_coupon.getBg() == 0){
                table_layout.setBackgroundResource(R.drawable.ic_paymentone);
                table_layout_exchange.setBackgroundResource(R.drawable.ic_paymentone);
            }else{
                table_layout.setBackgroundResource(R.drawable.ic_paymenttwo);
                table_layout_exchange.setBackgroundResource(R.drawable.ic_paymenttwo);
            }
            tv_denomination.setText(payMentCoupon_coupon.getDenomination());
            tv_deno.setText(payMentCoupon_coupon.getDeno());
            tv_coupontime.setText(payMentCoupon_coupon.getTime());
        }
        if(exchangeCoupon_coupon == null){
            toast("2");
            ll_exchange.setVisibility(View.GONE);
            tv_noneExchage.setVisibility(View.VISIBLE);
        }else{
            ll_exchange.setVisibility(View.VISIBLE);
            tv_noneExchage.setVisibility(View.GONE);
            if(exchangeCoupon_coupon.getBg() == 0){
                table_layout_exchange.setBackgroundResource(R.drawable.ic_paymentone);
            }else{
                table_layout_exchange.setBackgroundResource(R.drawable.ic_paymenttwo);
            }
            tv_denomination_exchange.setText(exchangeCoupon_coupon.getDenomination());
            tv_deno_exchange.setText(exchangeCoupon_coupon.getDeno());
            tv_coupontime_exchange.setText(exchangeCoupon_coupon.getTime());

        }
        tv_shopping_allmoney = (TextView) findViewById(R.id.tv_shopping_allmoney);
        tv_shopping_allmoney.setText(price);
        iv_payType = (ImageView) findViewById(R.id.iv_payType);
        lv_goods = (ListView) findViewById(R.id.lv_goods);
        shoppingCarPayAdapter = new ShoppingCarPayAdapter(this, shopCartBeanList);
        lv_goods.setAdapter(shoppingCarPayAdapter);

        if("微信".equals(pay_type)){
            iv_payType.setImageResource(R.drawable.ic_payment_by_wx);
        } else if ("支付宝".equals(pay_type)) {
            iv_payType.setImageResource(R.drawable.ic_payment_by_alipay);
        } else {
            toast("线下支付");
            iv_payType.setImageResource(R.drawable.ic_cash);
        }
        tv_account.setOnClickListener(this);

    }
    /**
     *
     * 获取支付宝支付信息
     * */
    private void getAlipay() {
        showCustomLoadBar("加载中");
        RequestParams params = new RequestParams(Config.Api.supermarketOrderPay);
        params.addBodyParameter("order_id",orderId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG获取支付宝支付信息"+result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result,"data");
                if(errCode == 0){
                    String orderId_long = JsonUtils.getInfo(data,"name");
                    String totalFee = JsonUtils.getInfo(data,"total");
//                    String productInfo = JsonUtils.getInfo(data,"content");
                    if(totalFee == null){
                        toast("返回为null");
                    }else{
                        AliUtils.pay(ShoppingCartPayActivity.this, mHandler, orderId_long,totalFee, "http://115.28.107.176/chang_zhi/api/index.php/Api/Alipay/alipay");
                    }
                }else{
                    toast("获取失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });

    }

    /**
     * 获取微信支付信息
     *
     * */
    public void getWeiInfo(){

        WxPaymentUtils wxPaymentUtils = new WxPaymentUtils(ShoppingCartPayActivity.this, order_long);
        wxPaymentUtils.payment();
        forward(OrderRecord.class);

        Dlog.e("GG获取微信支付完毕");

//
    }

    /**
     * 支付宝支付回调;
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AliUtils.SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    //String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(ShoppingCartPayActivity.this, "支付成功",
                                Toast.LENGTH_SHORT).show();
                        //支付成功;  进行操作
                        //修改后台订单状态;
                        forward(OrderActivity.class);
//                        modifyOrderStatus();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(ShoppingCartPayActivity.this, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(ShoppingCartPayActivity.this, "支付失败",
                                    Toast.LENGTH_SHORT).show();
                        }

//                        setResult(BACK_ORDER_LIST_RESULT_CODE);
                        onBackPressed();
                    }
                    break;
                }
                case AliUtils.SDK_CHECK_FLAG: {
                    Toast.makeText(ShoppingCartPayActivity.this, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_account:
                if("微信".equals(pay_type)){
                    Dlog.e("GG微信pay  "+orderId);
                    getWeiInfo();
                } else if ("支付宝".equals(pay_type)) {
                    Dlog.e("GG支付宝pay  "+orderId);
                    getAlipay();
                } else {
                    toast("线下支付");
                    Dlog.e("GG微信pay  "+orderId);
                    finish();
                }
                break;
        }
    }
}
